using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using System.ComponentModel.DataAnnotations;

namespace Luka;

/// <summary>
/// 结果过滤器
/// </summary>
[NotScanned]
internal sealed class UnifyResultFilter : IAsyncActionFilter, IAsyncResultFilter
{
    /// <summary>
    /// 重写方法
    /// </summary>
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        try
        {
            // 执行 Action 并获取结果
            var actionResult = await next();
            // 如果出现异常，则不会进入该过滤器
            if (actionResult.Exception != null) return;
            // 判断状态码是否为空
            if (actionResult.Result is IStatusCodeActionResult statusCodeResult && statusCodeResult.StatusCode != null)
            {
                if (statusCodeResult.StatusCode.Value < 200 || statusCodeResult.StatusCode.Value > 299)
                {
                    actionResult.Result = context.ReturnResult(actionResult.Result, true);
                }
            }
            // 是否错误类型
            if (actionResult.Result is BadRequestObjectResult badRequestObjectResult)
            {
                actionResult.Result = context.ReturnResult(badRequestObjectResult?.Value, true);
            }
            else
            {
                IActionResult? result = default;
                // 检查是否是有效的结果（可进行规范化的结果）
                if (UnifyResultExtensions.CheckVaild(actionResult.Result, out var data))
                {
                    result = context.ReturnResult(data);
                }
                // 不能规范化则跳过
                if (result == null)
                    return;
                actionResult.Result = result;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    /// <summary>
    /// 结果类型验证
    /// </summary>
    /// <returns></returns>
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        try
        {
            // 捕获字段验证结果
            if (!context.ModelState.IsValid)
            {
                string errorMsg = "参数输入格式不正确！";
                //获取最后一个手动追加的错误信息
                var validationResults = context.ModelState
                    .Values
                    .SelectMany(v => v.Errors)
                    .Select(e => new ValidationResult(e.ErrorMessage))
                    .LastOrDefault();
                if (validationResults != null && !string.IsNullOrWhiteSpace(validationResults.ErrorMessage))
                {
                    errorMsg = validationResults.ErrorMessage.Contains("field is required") ? "请输入必填项！" : validationResults.ErrorMessage;
                    // 将验证结果传递给下一个操作
                    context.Result = context.ReturnResult(errorMsg, true);
                }
                // 继续执行下一个操作
                await next();
            }
            else
            {
                //继续执行返回结果
                context.Result = (await next()).Result;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}